<!doctype html>
<html lang="zh-CN">

<head>
    <!-- 必须的 meta 标签 -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap 的 CSS 文件 -->
    <link href="./css/bootstrap@5.1.3/bootstrap.min.css" rel="stylesheet">

    <title>注册</title>
    <style>
        .login_block {
            border: 1px solid #ccc;
            padding: 30px 25px;
            border-radius: 5px;
            box-shadow: 1px 1px 2px burlywood;
        }
    </style>
</head>

<body>
<!-- 页面导航 -->
<script src="./js/nav.js"></script>
<!-- /页面导航 -->


<div class="container mt-5">

    <div class="row justify-content-center">
        <div class="col-xs-12 col-sm-8 clo-md-4 login_block">
            <form id="registForm">
                <div class="mb-3">
                    <label for="usernameInput" class="form-label visually-hidden">用户名</label>
                    <input type="text" class="form-control" id="usernameInput" aria-describedby="emailHelp">
                    <div id="emailHelp1" class="form-text"></div>
                </div>
                <div class="mb-3">
                    <label for="passwordInput" class="form-label visually-hidden">密码</label>
                    <input type="password" class="form-control" id="passwordInput">
                    <div id="emailHelp2" class="form-text">请输入密码</div>
                </div>
                <div class="mb-3">
                    <label for="rePasswordInput" class="form-label visually-hidden">密码</label>
                    <input type="password" class="form-control" id="rePasswordInput">
                    <div id="emailHelp3" class="form-text d-flex justify-content-between">
                        <span id="confirmpwdspan">请确认密码</span>
                        <a href="login.html">去登录</a>
                    </div>
                </div>
                <button type="button" id="but" class="btn btn-primary w-100">注册</button>
            </form>
        </div>
    </div>
</div>
<script src="./js/bootstrap@5.1.3/bootstrap.bundle.min.js"></script>
<script src="./js/just-validate@3.8.1/just-validate.production.min.js"></script>
<script type="text/javascript">
    let username = document.getElementById("usernameInput");
    let userpwd=document.getElementById("passwordInput");
    let confirmpwd=document.getElementById("rePasswordInput");
    let namespan = document.getElementById("emailHelp1");
    let pwdspan=document.getElementById("emailHelp2");
    let confirspan=document.getElementById("confirmpwdspan");

    //给用户名注册失聚焦事件
    username.onblur = function () {
        if (username.value === "") {
            //alert("用户名不能为空!");
            namespan.innerText = "用户名不能为空!";
            username.style.border="1px solid red";
        }
        else if (username.value.length < 2 || username.value.length > 14) {
            //alert("用户名必须在6-14位!");
            namespan.innerText = "用户名必须在2-14位!";
            username.style.border="1px solid red";
        }else{
            username.addEventListener("blur",function (){
                let xhr=new XMLHttpRequest();
                xhr.onreadystatechange=function (){
                    if (xhr.readyState == 4){
                        if (this.status == 404) {
                            alert("对不起，您访问的资源不存在，请检查请求路径")
                        } else if(this.status == 500){
                            alert("对不起，服务器发生了严重的内部错误，请联系管理员")
                        } else if(this.status == 200){
                            responseJson = eval("(" + this.responseText + ")");
                            //console.log(typeof testJson);-->object
                            namespan.innerHTML=responseJson.message;
                        }
                    }
                }
                xhr.open("Get","/shopping/check.user?t="+Math.random()+"&username="+username.value,false)
                xhr.send()
            },true);
            username.style.border="1px solid green";
        }
    }
    //给用户名注册聚焦事件
    username.onfocus = function () {
        if (username.value != "") {
            namespan.value = "";
        }
        namespan.innerText = "";
    }

    //给用密码注册聚焦事件
    userpwd.onfocus=function(){
        if (userpwd.value != "") {
            pwdspan.value = "";
        }
        pwdspan.innerText = "";
    }
    //给用密码注册失聚焦事件
    userpwd.onblur=function(){
        if (userpwd.value === "") {
            //alert("用户名不能为空!");
            pwdspan.innerText = "密码不能为空!";
            userpwd.style.border="1px solid red";
        }else if (userpwd.value.length < 2 || userpwd.value.length > 14) {
            //alert("用户名必须在6-14位!");
            pwdspan.innerText = "密码必须在2-14位!";
            userpwd.style.border="1px solid red";
        } else{
            userpwd.style.border="1px solid green";
        }
    }


    //给用确认密码注册聚焦事件
    confirmpwd.onfocus=function(){
        if (confirmpwd.value != "") {
            confirspan.value = "";
        }
        confirspan.innerText = "";
    }
    //给用确认密码注册失聚焦事件
    confirmpwd.onblur=function(){
        if (confirmpwd.value === "") {
            //alert("确认密码不能为空!");
            confirspan.innerText = "确认密码为空!";
            confirmpwd.style.border="1px solid red";
        }else if (confirmpwd.value != userpwd.value) {
            //alert("确认密码与原密码不符!");
            confirspan.innerText = "确认密码与原密码不符!";
            confirmpwd.style.border="1px solid red";
        } else{
            confirmpwd.style.border="1px solid green";
        }
    }

    //给提交按钮注册发送请求事件
        document.getElementById("but").onclick=function (){
            console.log(namespan.value);
            let xhr=new XMLHttpRequest();
            xhr.onreadystatechange=function (){
                if (xhr.readyState == 4){
                    if (this.status == 404) {
                        alert("对不起，您访问的资源不存在，请检查请求路径")
                    } else if(this.status == 500){
                        alert("对不起，服务器发生了严重的内部错误，请联系管理员")
                    } else if(this.status == 200){
                        responseJson = eval("(" + this.responseText + ")");
                        // namespan.innerHTML=responseJson.message;
                        alert(responseJson.message);
                    }
                }
            }
            xhr.open("Get","/shopping/register.user?t="+Math.random()+"&username="+username.value+"&password="+userpwd.value,true);
            xhr.send();
    }
</script>
<!--<script>
    //1.构建JustValidat实例对象
    const validation = new JustValidate("#registForm", {
        errorFieldCssClass: 'is-invalid',
        errorLableStyle: {
            fontSize: '14px',
            color: '#dc3545',
        },
        successFieldCssClass: 'is-valid',
        successLabelStyle: {
            fontSize: '14px',
            color: '#20b418'
        },
        focusInvalidField: false,
        lockForm: true,
    });

    document.querySelector("#usernameInput")
        ?.addEventListener('blur',()=>{
            let value=document.querySelector("#usernameInput").value;
            console.log(value);
            fetch("check.user?username="+value).then(response=>response.json())
                .then(data=> {
                    console.log(typeof data);
                    if (data.flag) {
                        validation.showSuccessLabels({
                            '#usernameInput':'可以使用',
                        });
                    }else {
                        validation.showErrors({
                            '#usernameInput':'用户名已存在',
                        });
                    }
                });
        });
    validation.addField("#usernameInput",[
        {
            rule: 'required',//必须填写
            errorMessage: '用户名必须填写'
        },
        {
            validator:()=>{
                //获得yonghu
                //发送异步请求
                return ()=>window.fakeFetch(500);
            },
                errorMessage:'name already exits',
        },
    ]);
    validation.addField('#passwordInput',[
        {
            rule:'required'
        },
    ])
    .addField('#repasswordInput',[
        {
            validator:(value,fields)=>{
            if(
                fields['#example2_password'] &&
                fields['#example2_password'].elem
              ){
                const repeatPasswordValue=
                fields['#example2_password'].elem.value;
                return value === reatPasswordValue;
              }
              return true;
            },
            errorMessage:'Password should be the same'
        },
    ]);
     validation.onSuccess((event)=>{
             event.preventDefault();
             //获得表单的数据
             let formData=new FormData();
             let username=document.querySelector("#usernameInput").value;
             let pwd=document.querySelector("#passwordIput").value;
             //追加数据
             formData.append("username",);
             formData.append("pwd");
             //执行注册请求
             fetch("register.user",{
                   method:"POST",
                   body:formData
             }).then(response=>response.json()).then(data=>console.log(data))
                   //如果注册成功跳转到login.html
                   if(data.flag&&data.code===20020){
                        location.href="login.html";
                   }else{
                        console.log(data.message);
                   }
                 }
             })
     });
</script>-->
</body>

</html>